#pragma once

#include <iostream>
#include <vector>
#include <semaphore.h>
#include <pthread.h>

namespace ns_ring_queue
{
    const int g_cap_default =10;
    template<class T>
    class RingQueue
    {
    public:
        RingQueue(int cap = g_cap_default)
            :_ring_queue(cap),_cap(cap),_c_step(0),_p_step(0)
        {
            sem_init(&_blank_sem,0,cap);
            sem_init(&_data_sem,0,0);

            pthread_mutex_init(&_c_mtx,nullptr);
            pthread_mutex_init(&_p_mtx,nullptr);
        }
        ~RingQueue()
        {
            sem_destroy(&_blank_sem);
            sem_destroy(&_data_sem);

            pthread_mutex_destroy(&_c_mtx);
            pthread_mutex_destroy(&_p_mtx);
        }
        void pop(T* out)
        {
            sem_wait(&_data_sem);

            pthread_mutex_lock(&_c_mtx);
            *out = _ring_queue[_c_step];
            _c_step++;
            _c_step %= _cap;
            pthread_mutex_unlock(&_c_mtx);

            sem_post(&_blank_sem);

        }
        void push(const T& in)//==生产
        {
            sem_wait(&_blank_sem);

            pthread_mutex_lock(&_p_mtx);
            _ring_queue[_p_step] = in;
            _p_step++;
            _p_step %= _cap;
            pthread_mutex_unlock(&_p_mtx);

            sem_post(&_data_sem);

        }
    private:
        std::vector<T> _ring_queue;
        int _cap;
        sem_t _blank_sem;
        sem_t _data_sem;
        int _c_step;
        int _p_step;
        pthread_mutex_t _c_mtx;
        pthread_mutex_t _p_mtx;
    };
    
} // namespace ns_ring_queue
